﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BabyShop.Site.Data
{
    public class EntityPager<T> : List<T>
    {
        private int _pageSize = 10;
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }

        private int _pageIndex = 1;
        public int PageIndex
        {
            get { return _pageIndex; }
            set { _pageIndex = value; }
        }

        public int TotalPages { 
            get { return Math.Abs(TotalCount - 1)/PageSize + 1; }
        }

        public int TotalCount
        {
            get
            {
                return _source == null ? 0 : _source.Count();
            }
        }

        private readonly IQueryable<T> _source;

        public EntityPager(IQueryable<T> source, int pageIndex, int pageSize = 10, string sortField = null, string sortKey = "ASC")
        {
            PageIndex = pageIndex;
            _source = source;
            _pageSize = pageSize;

            sortField = sortField ?? default(T).GetKeyName<T>();
            AddRange(source.OrderUsingSortExpression(sortField + " " + sortKey.ToUpper())
                         .Skip((PageIndex - 1)*PageSize).Take(PageSize).ToList());
        }
    }
}